#!/usr/bin/env python

# This script simply downloads waf to the current directory

# from __future__ import print_function
# import os, sys, stat, hashlib, subprocess

# WAFRELEASE = "master.zip"
# # https://gitee.com/william135/waf-waf-2.0.9.git
# #WAFURLS    = ["https://waf.io/" + WAFRELEASE,
# WAFURLS    = ["https://gitee.com/william135/waf-2.0.9/repository/archive/" + WAFRELEASE,
              # "https://gitee.com/william135/waf-2.0.9/repository/archive/" + WAFRELEASE]
# SHA256HASH = "2a8e0816f023995e557f79ea8940d322bec18f286917c8f9a6fa2dc3875dfa48"

# if os.path.exists("waf"):
    # wafver = subprocess.check_output([sys.executable, './waf', '--version']).decode()
    # if WAFRELEASE.split('-')[1] == wafver.split(' ')[1]:
        # print("Found 'waf', skipping download.")
        # sys.exit(0)

# try:
    # from urllib.request import urlopen, URLError
# except:
    # from urllib2 import urlopen, URLError

# waf = None

# for WAFURL in WAFURLS:
    # try:
        # print("Downloading {}...".format(repr(WAFURL)))
        
        # waf = urlopen(WAFURL).read()
        # break
    # except URLError:
        # print("Download failed.")

# if not waf:
    # print("Could not download {}.".format(repr(WAFRELEASE)))

    # sys.exit(1)

# if SHA256HASH == hashlib.sha256(waf).hexdigest():
    # with open("waf", "wb") as wf:
        # wf.write(waf)

    # os.chmod("waf", os.stat("waf").st_mode | stat.S_IXUSR)
    # print("Checksum verified.")
# else:
    # print("The checksum of the downloaded file does not match!")
    # print(" - got:      {}".format(hashlib.sha256(waf).hexdigest()))
    # print(" - expected: {}".format(SHA256HASH))
    # print("Please download and verify the file manually.")

    # sys.exit(1)
    
   
from __future__ import print_function
import os, sys, subprocess

WAFREPO = "https://gitee.com/william135/waf-2.0.9.git"
DEST_DIR = "waf"  # 目标目录，用于存放克隆下来的仓库

# 如果目录已经存在并且是一个 Git 仓库，直接跳过克隆
if os.path.exists(DEST_DIR):
    if os.path.isdir(os.path.join(DEST_DIR, ".git")):
        print(f"Git repository '{DEST_DIR}' already exists, skipping clone.")
    else:
        print(f"'{DEST_DIR}' exists but is not a git repository. Please remove it and try again.")
    sys.exit(0)

# 使用 git clone 克隆仓库
try:
    print(f"Cloning repository from {WAFREPO}...")
    subprocess.check_call(["git", "clone", WAFREPO, DEST_DIR])
    print(f"Repository cloned into '{DEST_DIR}'.")
except subprocess.CalledProcessError as e:
    print(f"Git clone failed: {e}")
    sys.exit(1)

# 切换到仓库目录并获取仓库版本
try:
    print("Checking out the latest version...")
    subprocess.check_call(["git", "-C", DEST_DIR, "checkout", "master"])
    wafver = subprocess.check_output([sys.executable, os.path.join(DEST_DIR, 'waf'), '--version']).decode()
    print(f"Found 'waf' version: {wafver}")
except subprocess.CalledProcessError as e:
    print(f"Error during git operations or waf version check: {e}")
    sys.exit(1)